package com.landian.commons.base.converter;


import com.landian.commons.base.utils.BeanUtilsProxy;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Convert
 *
 * @author caojl
 * @create 2017/12/18
 **/
public abstract class AbstractConvert<S,T> implements Convert<S,T>{

    /**
     * 源类
     */
    protected Class<S> srcClass;

    /**
     * 目标类
     */
    protected Class<T> targetClass;

    /**
     * 回调
     */
    protected ConvertHandler<S,T> handler;

    /**
     *
     * @param srcList
     * @return
     */
    @Override
    public List<T> convert(List<S> srcList){
        if(CollectionUtils.isEmpty(srcList)){
            return Collections.EMPTY_LIST;
        }
        List<T> targetList = new ArrayList<>();
        for (S src : srcList) {
            targetList.add(convert(src));
        }
        return targetList;
    }

    /**
     *
     * @param src
     * @return
     */
    @Override
    public T convert(S src){
        if(null == src){
            return null;
        }
        T target = null;
        try {
            target = targetClass.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        BeanUtilsProxy.copyPropertiesIgnoreNull(src,target);
        if(null != handler){
            handler.after(src,target);
        }
        return target;
    }
}
